<template>
  <div class="bgg">
    <div class="navbar">
      <div class="left-name">毫米波雷达</div>
      <div class="right-menu">
        <el-button
            class="back-workbench"
            @click="anb"
        >
          <span class="el-icon-back"/>
          {{ '返回工作台' }}
        </el-button>
      </div>
    </div>

    <div class="box">
      <div class="left">
        <radar-top-stat :radar-count="radarCount"></radar-top-stat>
        <div class="radar">
          <div class="title">实时雷达</div>
          <div class="forms">
            <div>
            <span>位置：</span
            >
              <el-select v-model="position" placeholder="请选择">
                <el-option
                    v-for="item in positionOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
            <div>
              <span>设备编码：</span>
              <el-select v-model="valueOfRadar" placeholder="请选择">
                <el-option v-for="item in optionss" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="img">
            <div class="l" id="l">
              <canvas id="canvas" style="width: 100%;"></canvas>
              <!-- <canvas id="heatCanvas" style="width: 100%;"></canvas> -->
            </div>
            <!-- <radar-info :personCount="personCount" :deviceInfo="deviceInfo" :sketch="sketch"></radar-info> -->
          </div>
        </div>
      </div>
      <div class="right">
        <radar-echart ref="chart"></radar-echart>
      </div>
    </div>
    <main-footer></main-footer>
  </div>
</template>

<script>
import Heatmap from "heatmap.js";
import heat from 'simpleheat'
import mqtt from "mqtt";
import {positon, radars, raderBg, radarsInfo} from "./config";
import sketch from "@/assets/radar/empty.png"
import bg from "@/assets/radar/bg/background.png";
import empty from '@/assets/radar/empty.png'
import radarInfo from "@/views/home/components/radar-info.vue";
import radarEchart from "@/views/home/components/radar-echart.vue";
import mainFooter from "@/layout/components/MainFooter.vue";
import {
  getRadarInfoList,
  getRadarTotle,
  installAdressList,
  radarDistribution,
} from "@/api/radar";
import RadarTopStat from "@/views/home/components/radar-top-stat.vue";
// const heat = 'https://cdn.jsdelivr.net/npm/simpleheat@0.4.0'
export default {
  name: "",
  components: {
    RadarTopStat,
    radarInfo,
    radarEchart,
    mainFooter
  },
  watch: {
    valueOfRadar: {
      immediate: true,
      handler: function (cur) {
        // this.bg = (cur!=='')? raderBg(cur): this.empty
        // this.bg = (cur!=='')? this.floor[cur]: this.empty
        this.bg
        this.sketch = (cur!=='')?this.floor[cur]: this.empty;
        this.data = [];
        this.deviceInfo = {
          code: "",
          installAdress: "",
          status: "",
        }
        if (cur !== "") {
          this.deviceInfo = this.optionss.filter(
              (item) => item.deviceCode == cur
          )[0];
          // this.ws.publish(cur);
          this.data = []
          this.initWs();
        }
      },
    },
    personCount:function (cur){
      if(!cur){
        this.initWs()
      }
    },
    position: {
      immediate: true,
      handler(cur) {
        if (cur != "") {
          this.getRadarByPosition(cur);
        }
      },
    }
  },
  data() {
    return {
      heatmapInstance:null,
      cacheId: [],
      optionss: [],
      valueOfRadar: "",
      floor: radars,
      data: [],
      ws: null,
      personCount: 0,
      deviceInfo: {
        code: "",
        installAdress: "",
        status: "",
      },
      sketch,
      bg,
      empty,
      people: {},
      trackPositions: {},
      radarCount: {
        allCount: "",
        dieCount: "",
        onlineCount: "",
      },
      chartBar: null,
      position: "",
      // 位置
      positionOptions: [],
      globalCoordinateSystemRange : {
        x: [0, 24.175],
        y: [0, 7.15]
      },
      tickInterval: 1
    };
  },
  beforeDestroy() {
    if (this.ws&&this.ws.connected === true) {
      // 断开mqtt连接
      this.ws.end(true)
    }
  },

  mounted() {
    // this.getTotal();
    // this.getFloors();
    // this.getPosition();
    this.init();
    let that = this;
    // that.heatmapInstance = h337.create({
    //   container:that.canvas,
    //   gradient: {//渐变颜色
    //       "0": "rgba(255,255,255,1)",//value为0的颜色
    //       "0.3": "#82ff6d",//value为500的颜色
    //       "0.8": "#f3ff6d",//value为1000的颜色
    //       "1": "#ff6d6d",//value为2000的颜色
    //     },
    //     // radius: 10,
    //     maxOpacity: 1,
    //     minOpacity: 0,
    //     blur: .75,
    //     // radius:30, //半径
    // })
    window.addEventListener("resize", () => {
      that.canvas.width = window.innerWidth / 2;
      that.canvas.height = window.innerHeight;
      that.resizeCanvas(
          that.backgroundImage.width,
          that.backgroundImage.height
      );
    });

    window.addEventListener("load", () => {
      that.canvas.width = window.innerWidth / 2;
      that.canvas.height = window.innerHeight;
      that.backgroundImage.src = that.bg;
    });
    for (var item in radars) {
      let obj = {
        value: item,
        label: item,
      };
      // if (item == "DEKP1245704") {
      //   this.valueOfRadar = "DEKP1245704";
      // }
      that.optionss.push(obj);
    }
    that.analogData()
  },
  computed: {
    trackDuration() {
      return this.getTrackDurationFromURLParams();
    },
    // heatCtx() {
    //   return this.heatCanvas.getContext("2d");
    // },
    // heatCanvas() {
    //   return document.getElementById("heatCanvas");
    // },
    ctx() {
      return this.canvas.getContext("2d");
    },
    canvas() {
      return document.getElementById("canvas");
    },
    backgroundImage() {
      return new Image();
    },
    areaWidth() {
      return document.getElementById("canvas").width;
    },
    areaHeight() {
      return document.getElementById("canvas").height;
    },
  },
  methods: {
    //模拟数据
    analogData(){
      this.valueOfRadar = 'DEKP1245719'
      setInterval(()=>{
      var datas = {
        DEKP1245715:{
          pointTargetDataR9rList:[]
        },
        DEKP1245716:{
          pointTargetDataR9rList:[]
        },
        DEKP1245717:{
          pointTargetDataR9rList:[]
        },
        DEKP1245718:{
          pointTargetDataR9rList:[]
        },
        DEKP1245719:{
          pointTargetDataR9rList:[]
        },
        DEKP1245720:{
          pointTargetDataR9rList:[]
        }
        }
        // var datas = {
        //   pointTargetDataR9rList:[]
        // }
        var arr = []
        for(let i = 0;i < 10;i++){
          let obj = {}
          obj.pointId = i
          obj.x = (Math.random() * (1.5 - (-0.5)) + (-0.5)).toFixed(1)
          obj.y = (Math.random() * (1.5 - (-0.5)) + (-0.5)).toFixed(1)
          arr.push(obj)
        }
        datas.DEKP1245715.pointTargetDataR9rList = arr
        datas.DEKP1245716.pointTargetDataR9rList = arr
        datas.DEKP1245717.pointTargetDataR9rList = arr
        datas.DEKP1245718.pointTargetDataR9rList = arr
        datas.DEKP1245719.pointTargetDataR9rList = arr
        datas.DEKP1245720.pointTargetDataR9rList = arr
        // datas.pointTargetDataR9rList = arr

        this.handleRadarInfo(datas)
      },800)
    },
    // 返回工作台
    anb() {
      this.$router.push('home')
    },
    init() {
      let that = this;
      that.chartBar = that.$echarts.init(that.$refs.chart.$refs["chart"]);
      that.chartBar.setOption(that.$refs.chart.options);
      window.addEventListener("resize", function () {
        that.chartBar.resize();
      });
    },
    getRadarsByPositon(){

    },
    //转换到大坐标系
    toGlobalCoordinates(x, y, x_offset, y_offset, theta, horizontal_direction) {
      theta = (theta * Math.PI) / 180;
      // 根据 horizontal_direction 的值决定如何使⽤⻆度 theta
      if (horizontal_direction === 'left') {
        theta = -theta;
      }
      var x_prime = (x * Math.cos(theta) - y * Math.sin(theta));
      var y_prime = (x * Math.sin(theta) + y * Math.cos(theta));
      x_prime += x_offset;
      y_prime += y_offset;
      return { x_prime, y_prime };
    },
    //转换像素坐标
    toPixelCoordinates(x, y) {
      // 需要知道大坐标系的范围和canvas的大小
      const [x_min, x_max] = this.globalCoordinateSystemRange.x;
      const [y_min, y_max] = this.globalCoordinateSystemRange.y;
      return {
        x_pixel: ((x - x_min) / (x_max - x_min)) * this.canvas.width,
        y_pixel: this.canvas.height - ((y - y_min) / (y_max - y_min)) * this.canvas.height,
      };
    },
    // 人员轨迹点随机生成颜色
    filterColor(objArray, id) {
      for (let i = 0; i < objArray.length; i++) {
        // 如果找到匹配的 id，则返回对应的 color 值
        if (objArray[i].id === id) {
          return objArray[i].color;
        }
      }
      return `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(
          Math.random() * 256
      )}, ${Math.floor(Math.random() * 256)})`;
    },
    initWs() {
      if (this.ws && this.ws.connected === true) {
        // 断开mqtt连接
        this.ws.end(true)
        this.personCount = 0
        this.trackPositions = {}
        this.$set(this.trackPositions, {})
        this.cacheId = []
        this.people = {}
        this.update()
      }
      this.connect()
    },
    connect() {
      let that = this;
      that.backgroundImage.src = that.bg;
      that.backgroundImage.onload = () => {
        that.resizeCanvas(
          that.backgroundImage.width,
          that.backgroundImage.height
          );
          that.update();
          // that.drawHeatmap()
      };
      // that.ws = mqtt.connect("ws://10.0.91.159:15675/ws");
      let radarList = [
        'DEKP1245701',
        'DEKP1245702',
        'DEKP1245703',
        'DEKP1245704',
        'DEKP1245719',
        'DEKP1245720',
      ]
      const ws = mqtt.connect('ws://10.102.5.9:15675/ws')
        ws.on('connect', () => {
          console.log('连接雷达${radarCode}成功')
          radarList.forEach(radarCode => {

            ws.subscribe(radarCode, err => {
            if (err) {
              console.error(`订阅雷达 ${radarCode} 的数据失败`);
            } else {
              console.log(`订阅雷达 ${radarCode} 的数据成功`);
            }
          })
        })
        })
        ws.on('message', (topic, message) => {
          // console.log(topic, 'topic')
          const data = JSON.parse(message.toString())
          // console.log(`收到雷达 ${radarCode} 的数据：`, data)
          // that.handleRadarInfo(data)
        })

      // that.ws.on("connect", (err) => {
      //   console.log(this.valueOfRadar, 'valueOfRadar')
      //   that.ws.subscribe(that.valueOfRadar, function (err) {
      //     if (!err) {
      //       console.log("雷达数据连接成功");
      //     }
      //   });
      // });
      // 'message'用于接收自己订阅的消息
      // that.ws.on("message", function (_, event) {
      //   that.data = [];
      //   const msg = new TextDecoder("utf-8").decode(event);
      //   var convertData = {}
      //   if (typeof msg == "string" && msg.length > 0) {
      //     convertData = JSON.parse(msg);
      //   }
      //   console.log(msg,'msg')
      //   console.log(convertData,'convertData')
      //   that.handleRadarInfo(convertData)
      // })

    },
    //
    handleRadarInfo(convertData) {
      this.data = []
      console.log('点数据----------------')
      console.log(convertData)
      // if (this.valueOfRadar == convertData.deviceCode) {
        // if (convertData.pointTargetDataR9rList && convertData.pointTargetDataR9rList.length !== 0) {
          for(var rd in  convertData){
            console.log(rd)
            let arr = convertData[rd].pointTargetDataR9rList.map(item=>{
              let info = radarsInfo[rd]
              const {
                  x_prime,
                  y_prime
                } = this.toGlobalCoordinates(item.x, item.y, info.position.x, info.position.y, info.orientation, info.horizontal_direction)
                const {x_pixel, y_pixel} = this.toPixelCoordinates(x_prime, y_prime)
                var person = {
                  id: item.pointId,
                  x: x_pixel,
                  y: y_pixel,
                  color: this.filterColor(this.cacheId, item.pointId)
                };
                return person;
            })
            console.log(arr)
            this.data = this.data.concat(arr)
            this.data = this.data.map((item,index)=>{
              item.id = index
              return item
            })
          }
          console.log('总数据-----------')
          console.log(this.data)
          this.personCount = this.data.length;
          this.cacheId = this.data;
          this.drawPerson()
          // console.log('-----------------')
          // console.log("雷达数据")
          // console.log(convertData.pointTargetDataR9rList);
          // var arr = []
          // this.data = convertData.pointTargetDataR9rList.map(
          //     (item, index) => {
          //       let info = radarsInfo[this.valueOfRadar]
          //       const {
          //         x_prime,
          //         y_prime
          //       } = this.toGlobalCoordinates(item.x, item.y, info.position.x, info.position.y, info.orientation, info.horizontal_direction)
          //       console.log('-----------------')
          //       console.log('大坐标系')
          //       console.log(x_prime + ":" + y_prime)
          //       const {x_pixel, y_pixel} = this.toPixelCoordinates(x_prime, y_prime)
          //       console.log('-----------------')
          //       console.log('像素坐标')
          //       console.log(x_pixel + ":" + y_pixel)
          //       var person = {
          //         id: item.pointId,
          //         x: x_pixel,
          //         y: y_pixel,
          //         color: this.filterColor(this.cacheId, item.pointId)
          //       };
          //       return person;
          //     }
          // );
          // this.personCount = this.data.length;
          // console.log(this.data,':this.data',this.cacheId,':this.cacheid')
          // this.cacheId = this.data;
          // this.drawPerson()
        // }
      // } else {
      //   console.log(222222222)
      //   this.ws.end(true)
      // }
    },
    // 绘制人员轨迹
    drawPerson() {
      for (const person of this.data) {
        const id = person.id;
        if (!(id in this.people)) {
          this.people[id] = person;
          this.trackPositions[id] = [];
        } else {
          Object.assign(this.people[id], person);
        }
        this.trackPositions[id].push({
          x: person.x,
          y: person.y,
          timestamp: Date.now(),
        });
        while (
            this.trackPositions[id].length > 0 &&
            Date.now() - this.trackPositions[id][0].timestamp >
            this.trackDuration * 1000
            ) {
          this.trackPositions[id].shift();
        }
      }
    },
    drawHeatmap(){
      let heatMapData = [];
      for (let id in this.people) {
        let person = this.people[id];
        heatMapData.push([person.x, person.y, 0.7]); // 第三个参数是热力图的强度，你可以根据需要进行调整
      }
      console.log('===========')
      console.log(heatMapData)
      // 更新热力图数据并绘制
      heat('canvas').data(heatMapData).draw();
    },
    deleteHotMap(){
      var heatmapBox = this.canvas;
      if(heatmapBox.children.length>1){
        var oldCanvas = heatmapBox.children[1];
        heatmapBox.removeChild(oldCanvas);
      }
    },
    drawHeat(){
      this.deleteHotMap()
      var heatmapInstance = Heatmap.create({
      container:this.canvas,
      // gradient: {//渐变颜色
      //     "0": "rgba(255,255,255,1)",//value为0的颜色
      //     "0.3": "#82ff6d",//value为500的颜色
      //     "0.8": "#f3ff6d",//value为1000的颜色
      //     "1": "#ff6d6d",//value为2000的颜色
      //   },
        // radius: 10,
        // maxOpacity: 1,
        // minOpacity: 0,
        radius:30, //半径
    })
      let heatMapData = [];
      for (let id in this.people) {
        let person = this.people[id];
        heatMapData.push({x:person.x, y:person.y, value:1}); // 第三个参数是热力图的强度，你可以根据需要进行调整
        heatMapData.push({x:15, y:3, value:3}); // 第三个参数是热力图的强度，你可以根据需要进行调整

      }
      console.log('===========')
      console.log(heatMapData)
      console.log(heatmapInstance)
      // 更新热力图数据并绘制
      heatmapInstance.setData({max:5,min:0,data:heatMapData})
    },
    update() {
      let that = this;
      // that.ctx.globalAlpha = 0.8
      that.ctx.clearRect(0, 0, this.canvas.width, that.canvas.height);
      that.ctx.drawImage(that.backgroundImage, 0, 0, that.canvas.width, that.canvas.height);
      // that.drawHeatmap()
      that.drawHeat()

      that.drawAxis();
      for (const id in that.people) {
        const person = that.people[id];
        const positions = that.trackPositions[id];

        that.ctx.beginPath();
        that.ctx.fillStyle = person.color || 'red';
        that.ctx.arc(person.x, person.y, 5, 0, 2 * Math.PI);
        that.ctx.fill();
        that.ctx.beginPath();
        that.ctx.strokeStyle = person.color || 'white';

        that.ctx.lineWidth = 2;
        const currentTime = Date.now();
        for (let i = positions?.length - 1; i >= 0; i--) {
          const position = positions[i];
          if (
              currentTime - position.timestamp >
              that.trackDuration * 300
          ) {
            break;
          }
          that.ctx.globalAlpha =
              (currentTime - position.timestamp) / (that.trackDuration * 300);
          if (i === positions.length - 1) {
            that.ctx.moveTo(position.x, position.y);
          } else {
            that.ctx.lineTo(position.x, position.y);
          }
        }
        that.ctx.stroke();
        that.ctx.globalAlpha = 1;
      }
      requestAnimationFrame(that.update);
    },
    // 画刻度标尺
    drawAxis() {
      let that = this;
      that.ctx.beginPath();
      that.ctx.strokeStyle = '#fff';
      that.ctx.lineWidth = 2;
      that.ctx.moveTo(0, 0);
      that.ctx.lineTo(that.canvas.width, 0);
      that.ctx.moveTo(0, 0);
      that.ctx.lineTo(0, that.canvas.height);

      that.ctx.font = "20px Arial";
      // 使用大坐标系的单位来绘制刻度，每tickInterval个单位一个刻度
      const [x_min, x_max] = that.globalCoordinateSystemRange.x;
      const [y_min, y_max] = that.globalCoordinateSystemRange.y;
      for (let x = x_min; x <= x_max; x += that.tickInterval) {
        const x_pixel = ((x - x_min) / (x_max - x_min)) * that.canvas.width;
        that.ctx.moveTo(x_pixel, 0);
        that.ctx.lineTo(x_pixel, 5);
        that.ctx.strokeText(x.toString(), x_pixel - 5, 20);
      }

      for (let y = y_min; y <= y_max; y += that.tickInterval) {
        const y_pixel = that.canvas.height - ((y - y_min) / (y_max - y_min)) * that.canvas.height;
        that.ctx.moveTo(0, y_pixel);
        that.ctx.lineTo(5, y_pixel);
        that.ctx.strokeText(y.toString(), 10, y_pixel + 5);
      }

      that.ctx.stroke();
    },
    resizeCanvas(width, height) {
      let that = this;
      that.canvas.width = width;
      that.canvas.height = height;
      that.ctx.drawImage(
          that.backgroundImage,
          0,
          0,
          that.canvas.width,
          that.canvas.height
      );
    },
    getTrackDurationFromURLParams() {
      const urlParams = new URLSearchParams(window.location.search);
      return parseInt(urlParams.get("trackDuration")) || 5;
    },
    async getTotal() {
      getRadarTotle().then((res) => {
        this.radarCount = { ...res.data };
      });
    },
    async getFloors() {
      let that = this;
      radarDistribution().then(({ data }) => {
        Object.keys(data).forEach((item) => {
          that.$refs.chart.options.yAxis[0].data.push(item);
        });
        Object.values(data).forEach((item) => {
          that.$refs.chart.options.series[0].data.push(item);
        });
        that.init();
      });
    },
    async getPosition() {
      installAdressList().then(({ data }) => {
        data.forEach((item) => {
          let obj = {};
          obj.value = item;
          obj.label = item;
          this.positionOptions.push(obj);
        });
        this.position = this.positionOptions[14].value;
      });
    },
    async getRadarByPosition(installAdress) {
      getRadarInfoList({ installAdress }).then(({ data }) => {
        this.valueOfRadar = ''
        this.optionss = data.map((item) => {
          item.value = item.deviceCode;
          item.label = item.deviceCode;
          return item;
        });
        if (this.optionss.length != 0) {
          this.valueOfRadar = this.optionss[0].value;
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.point {
  display: block;
  width: 7px;
  height: 7px;
  border-radius: 50%;
  margin-right: 5px;
}
.icon1 {
  background-image: url("~@/assets/second/radar_total@2x.png") !important;
  background-position: 50% 50% !important;
}
.icon2 {
  background-image: url("~@/assets/second/radar_using@2x.png") !important;
  background-position: 50% 50% !important;
}
.icon3 {
  background-image: url("~@/assets/second/radar_fail@2x.png") !important;
  background-position: 50% 50% !important;
}
.box {
  display: flex;
  margin: 20px;
  justify-content: space-between;
  height: 780px;
  .left {
    width: 65%;
    display: flex;
    flex-direction: column;

    .radar {
      flex: 1;
      background: #fff;
      padding: 16px;
      .title {
        border-left: 4px solid #2871fe;
        padding-left: 8px;
        font-family: "HarmonyOS Sans SC";
        font-style: normal;
        font-weight: 700;
        font-size: 16px;
        color: #000000;
        margin-bottom: 28px;
      }
      .forms {
        display: flex;
        font-family: "HarmonyOS Sans SC";
        font-style: normal;
        font-weight: 400;
        font-size: 14px;
        color: #333333;
        margin-bottom: 20px;
        /deep/ .el-select {
          width: 380px;
        }
        > div:first-child {
          margin-right: 30px;
        }
      }
      .img {
        height: 510px;
        display: flex;
        justify-content: space-between;
        .l {
          height: 100%;
          width: 70%;
          background: #EFF5FF;
          border-radius: 8px;
          overflow: hidden;
        }

      }
    }
  }
  .right {
    width: 30%;
    margin-left: 20px;
    flex: 1;
    background: #fff;
    padding: 20px;
    display: flex;
    flex-direction: column;

  }
}
.navbar {
  height: 50px;
  overflow: hidden;
  position: relative;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);

  .hamburger-container {
    line-height: 46px;
    height: 100%;
    float: left;
    cursor: pointer;
    transition: background .3s;
    -webkit-tap-highlight-color:transparent;

    &:hover {
      background: rgba(0, 0, 0, .025)
    }
  }

  .breadcrumb-container {
    float: left;
  }

  .errLog-container {
    display: inline-block;
    vertical-align: top;
  }

  .left-name{
    float: left;
    padding: 10px 16px;
    font-size: 18px;
    font-weight: 700;
    line-height: 27px;
  }
  .right-menu {
    float: right;
    height: 100%;
    line-height: 50px;

    &:focus {
      outline: none;
    }

    .back-workbench {
      display: inline-block;
      position: relative;
      font-size: 12px;
      height: 32px;
      line-height: 32px;
      cursor: pointer;
      border: 1px solid #d8dce5;
      color: #495060;
      background: #fff;
      padding: 0 8px;
      margin-right: 8px;
      border-radius: 4px;
      &.active {
        background-color: #5282ec;
        color: #fff;
        border-color: #5282ec;
      }
    }

  }
}
</style>
